package com.dartfar.util;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.List;

/**
 * 文件工具类
 * @author 王琦
 *
 */

public class FileUtils {
	/**
	 * 得到指定目录的下文件路径集合
	 * @param path   路径
	 * @param ext    过滤后缀名
	 * @param isRecursion  是文件还是目录  
	 * @param fileList  需封装的list
	 */
	public static void list(String path, String ext, boolean isRecursion, List<String> fileList) {
		try {
			File f = new File(path);
			if (!f.exists()) {
				System.out.println("文件或目录不存在!");
				return;
			}

			if (f.isDirectory()) {

				File[] list = f.listFiles(getFileExtensionFilter(ext));
				for (int i = 0; i < list.length; i++) {
					fileList.add(list[i].toString());
				}
					
				list = f.listFiles(getNotDirFileFilter());
				for (int i = 0; i < list.length; i++)
					if (list[i].isDirectory() && isRecursion)
						list(list[i].toString(), ext, isRecursion, fileList);
			}

		} catch (Exception e) {
			System.out.println("IO error!/r/n" + e.toString());
		}
	}
	/**
	 *  指定扩展名过滤
	 * @param extension
	 * @return
	 */
	public static FilenameFilter getFileExtensionFilter(String extension) {
		final String _extension = extension;
		return new FilenameFilter() {
			public boolean accept(File file, String name) {
				boolean ret = name.endsWith(_extension);
				return ret;
			}
		};
	}
	/**
	 * 文件还是目录过滤
	 * @return
	 */
	public static FileFilter getNotDirFileFilter() {

		return new FileFilter() {

			public boolean accept(File file) {
				return file.isDirectory(); // 关键判断点
			}
		};
	}
	/**
     * 删除空目录
     * @param dir 将要删除的目录路径
     */
    private static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return 
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
          //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
}
